package com.offcn.controller;

import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import com.offcn.utils.FastDFSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class UploadController {
    @Value("${file.url}")
    public String url;

    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile file){
        //文件原始名
        String originalFilename = file.getOriginalFilename();
        //获取文件的后缀名
        String extension = StringUtils.getFilenameExtension(originalFilename);
        //创建工具类对象
        try {
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:fdfs_client.conf");
            String path = fastDFSClient.uploadFile(file.getBytes(), extension);
            String fileUrl = url + path;
            return new Result(true, StatusCode.OK,"上传成功",fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"上传失败",null);
        }

    }
}
